"use strict";

let canvas;
let gl;


let points = [];

// let g_points = [];
// var NumTimesToSubdivide = 5;
let IsFocus = false;
let vertices = [
    vec2(-0.8, 0.3),
    vec2(-0.5, 0.3),
    vec2(-0.5, 0),
    vec2(-0.8, 0)
];
let space = [];

let color = [
    vec4(1, 0, 0, 1),
    vec4(1, 0, 0, 1),
    vec4(1, 0, 0, 1),
    vec4(1, 0, 0, 1)
];

let FocusColor = [
    vec4(0.5, 0, 0, 1),
    vec4(0.5, 0, 0, 1),
    vec4(0.5, 0, 0, 1),
    vec4(0.5, 0, 0, 1)
];

let mat = new Float32Array([
    1.0, 0.0, 0.0, 0.0,
    0.0, 1.0, 0.0, 0.0,
    0.0, 0.0, 1.0, 0.0,
    0.0, 0.0, 0.0, 1.0,
]);

let matLoc;
let isBoxChoose = false;
let posX, posY;
// let selectBox;
// let canva;
// let ctx;
let mask;
// 记录之前的光标位置
let oldX = 0, oldY = 0;
window.onload = function init() {
    canvas = document.getElementById("gl-canvas");
    gl = WebGLUtils.setupWebGL(canvas);
    if (!gl) {
        alert("WebGL isn't available");
    }
    //
    //  Initialize our data for the Sierpinski Gasket
    //

    // First, initialize the corners of our gasket with three points.

    triangle(vertices)


    //  Configure WebGL
    //
    gl.viewport(0, 0, canvas.width, canvas.height);
    gl.clearColor(1.0, 1.0, 1.0, 1.0);

    //  Load shaders and initialize attribute buffers

    let program = initShaders(gl, "vertex-shader", "fragment-shader");
    gl.useProgram(program);

    // Load the data into the GPU


    let buffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, buffer);

    gl.bufferData(gl.ARRAY_BUFFER, flatten(color), gl.STATIC_DRAW);
    //获取a_color
    let a_Color = gl.getAttribLocation(program, "a_Color");
    //将点的颜色传递到变量u_FragColor中
    gl.vertexAttribPointer(a_Color, 4, gl.FLOAT, false, 0, 0);
    gl.enableVertexAttribArray(a_Color);


    buffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
    gl.bufferData(gl.ARRAY_BUFFER, flatten(points), gl.STATIC_DRAW);

    // Associate out shader variables with our data buffer

    let vPosition = gl.getAttribLocation(program, "vPosition");
    //
    matLoc = gl.getUniformLocation(program, 'mat');

    // console.dir(matLoc)
    gl.vertexAttribPointer(vPosition, 2, gl.FLOAT, false, 0, 0);
    gl.enableVertexAttribArray(vPosition);
    gl.uniformMatrix4fv(matLoc, false, mat);

    canvas.onmousedown = function (ev) {
        // click(ev, gl, canvas, vPosition)
        getFocus(ev, gl, canvas, a_Color);
    }
    canvas.onmousemove = function (ev) {
        move(ev, gl, canvas, vPosition);
    }
    canvas.onmouseup = function () {
        loseFocus(gl, a_Color);
    }
    render();
};

// 更新数据缓冲
function UpdateArrayBuffer(gl, data, numOfComponents, dataType, attribute) {
    let buffer = gl.createBuffer();
    if (!buffer) {
        console.log('Failed to create buffer object');
        return false;
    }

    gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
    gl.bufferData(gl.ARRAY_BUFFER, flatten(data), gl.STATIC_DRAW);

    gl.vertexAttribPointer(attribute, numOfComponents, dataType, false, 0, 0);
    gl.enableVertexAttribArray(attribute);

    gl.uniformMatrix4fv(matLoc, false, mat);
    return true;
}

// 鼠标抬起时失去焦点
function loseFocus(gl, a_Color) {
    IsFocus = false;
    // canvas.removeChild(selectBox)
    isBoxChoose = false;
    // console.log("mouseup")
    // mask = document.querySelector('.mask')
    // // mask.style.display = 'inline'
    // // console.dir(mask)
    // mask.style.display = "none";
    UpdateArrayBuffer(gl, color, 4, gl.FLOAT, a_Color);
    render()
}

// 鼠标按下时获取焦点
function getFocus(ev, gl, canvas, a_Color) {
    // let x = ev.clientX;
    // let y = ev.clientY;
    // let rect = ev.target.getBoundingClientRect();
    // x = x - rect.left
    // y = y - rect.top
    // x = -1.0 + x/(canvas.width/2)
    // y = 1.0 - y/(canvas.height/2)
    // console.log(x,y);
    // console.log(vertices[0][0],vertices[2][0])
    // console.log(vertices[0][0],vertices[2][0])

    let xy = getCursorPos(ev)
    let x = xy[0];
    let y = xy[1];
    oldX = x;
    oldY = y;
    if (x > vertices[0][0] && x < vertices[2][0] && y > vertices[2][1] && y < vertices[0][1]) {
        IsFocus = true;
        calculateSpace(x, y, ev)
        UpdateArrayBuffer(gl, FocusColor, 4, gl.FLOAT, a_Color);
        render()
    } else {
        IsFocus = false;
        isBoxChoose = true;
        mask = document.querySelector('.mask')
        mask.style.display = 'block'
        posX = ev.clientX ;
        posY = ev.clientY ;
        // canva = document.querySelector('canvas')
        // selectBox = document.createElement('div');
        mask.style.left = posX + "px";
        mask.style.top = posY + "px";
        // ctx = canva.getContext("2d");
        // canvas.appendChild(selectBox)
        // canvas.addEventListener("mousemove", function (ev) {
        //     selectBox.style.left = Math.min(ev.clientX, posX) + "px";
        //     selectBox.style.top = Math.min(ev.clientY, posY) + "px";
        //     selectBox.style.height = Math.abs(posY - ev.clientY) + "px";
        //     selectBox.style.width = Math.abs(posX - ev.clientX) + "px";
        //     canvas.addEventListener("mouseup", function () {
        //         selectBox.parentNode.removeChild(selectBox)
        //         // div.parentNode.removeChild(div);
        //     })
        // })
        // UpdateArrayBuffer(gl, color, 4, gl.FLOAT, a_Color);
        // render()
        // ctx.fillStyle = "#DDDDDD";
        // ctx.fillRect(0, 0, 400, 400);
        // ctx.strokeStyle = "black";
        // ctx.fillStyle = "gray";
        // ctx.lineWidth = 5;
        // ctx.fillRect(0,0,200,300);
        // ctx.strokeRect(0,0,200,200);
        document.onmouseup = function () {
            mask.style.display = 'none'
        }

    }
}

// else{
//     // console.log("hello")
//     if (isBoxChoose){
//         let x = ev.clientX;
//         let y = ev.clientY;
//         selectBox = document.createElement("div");
//         selectBox.className = "mask";
//         selectBox.style.left = Math.min(x, posX)+"px";
//         selectBox.style.top = Math.min(y, posY) + "px";
//         canvas.appendChild(selectBox);
//         // div.style.left = Math.min(ev.clientX, x) + "px";
//         // div.style.top = Math.min(ev.clientY, y) + "px";
//         selectBox.style.width = Math.abs(x - posX)+"px";
//         selectBox.style.height = Math.abs(y - posY)+"px";
//     }
// }

// 鼠标移动时根据IsFocus来判断是否需要移动
function move(ev, gl, canvas, vPosition) {
    if (IsFocus && !isBoxChoose) {
        let xy = getCursorPos(ev);
        let x = xy[0];
        let y = xy[1];
        // 平移的距离 x - oldX, y - oldY
        mat = new Float32Array([
            1.0, 0.0, 0.0, 0.0,
            0.0, 1.0, 0.0, 0.0,
            0.0, 0.0, 1.0, 0.0,
            x - oldX, y - oldY, 0.0, 1.0,
        ]);
        // console.log(mat)
        // console.log(x,y)
        // x= ((x - rect.left) - canvas.width/2)/(canvas.width/2);
        // y = (canvas.height/2 - (y - rect.top))/(canvas.height/2);
        // g_points.push(x)
        // g_points.push(y)
        // gl.clear(gl.COLOR_BUFFER_BIT)
        // for (let i=0; i<g_points.length;i+=2){
        //     // console.log(g_points[i])
        //     // gl.vertexAttrib3f(vPosition, g_points[i], g_points[i+1],0.0)
        //     // gl.drawArrays(gl.POINTS, 0, 4)
        // }
        // console.log(x,y)

        for (let i = 0; i < points.length; i++) {
            points[i][0] = x + space[i][0]

            points[i][1] = y + space[i][1]
        }

        UpdateArrayBuffer(gl, points, 2, gl.FLOAT, vPosition);
        oldX = x;
        oldY = y;
        render();
    }
    else if (isBoxChoose){

        // canvas.appendChild(selectBox);
        // let left = Math.min(ev.clientX, posX) ;
        // let top = Math.min(ev.clientY, posY) ;
        // let height = Math.abs(posY - ev.clientY) ;
        // let width = Math.abs(posX - ev.clientX) ;
        console.log("move")
        mask.style.left = Math.min(ev.clientX, posX) + "px";
        mask.style.top = Math.min(ev.clientY, posY) + "px";
        mask.style.width = Math.abs(posX - ev.clientX)+"px";
        mask.style.height = Math.abs(posY - ev.clientY)+"px";
        // ctx.fillRect(posX,posY,width,height)
    }

}


// 计算鼠标点击的点到四个顶点的间距
function calculateSpace(x, y, ev) {

    // let sumA = 0, sumB = 0;
    // for (let i = 0 ;i<points.length;i++){
    //     sumA = sumA + points[i][0];
    //     sumB = sumB + points[i][1];
    // }
    // let center = vec2(sumA/4, sumB/4);
    // console.log(center);
    for (let i = 0; i < points.length; i++) {
        space[i] = vec2(points[i][0] - x, points[i][1] - y)
    }
    // return center
    // console.log(space)
}

function triangle(array) {
    for (let i = 0; i < array.length; i++) {
        points.push(array[i])
    }
}


// function automove(){
//     // console.log('hello')
//     let xstep = 0.1
//     let ystep = 0.1
//     for(let i=0;i< points.length; i++){
//         points[i][0] += xstep
//
//         points[i][1] += ystep
//         // console.log(points[i])
//     }
//     // gl.clear( gl.COLOR_BUFFER_BIT );
//     var program = initShaders( gl, "vertex-shader", "fragment-shader" );
//     gl.useProgram( program );
//     var bufferId = gl.createBuffer();
//     gl.bindBuffer( gl.ARRAY_BUFFER, bufferId );
//     gl.bufferData( gl.ARRAY_BUFFER, flatten(points), gl.STATIC_DRAW );
//
//     // Associate out shader variables with our data buffer
//     var vPosition = gl.getAttribLocation( program, "vPosition" );
//     gl.vertexAttribPointer( vPosition, 2, gl.FLOAT, false, 0, 0 );
//     gl.enableVertexAttribArray( vPosition );
//     render();
// }

function render() {
    gl.clear(gl.COLOR_BUFFER_BIT);
    gl.drawArrays(gl.TRIANGLE_FAN, 0, points.length);
}

// 获取光标位置
function getCursorPos(ev) {
    let x = ev.clientX;
    let y = ev.clientY;
    // 返回值是一个 DOMRect 对象，这个对象是由该元素的 getClientRects() 方法返回的一组矩形的集合，就是该元素的 CSS 边框大小。
    // 返回的结果是包含完整元素的最小矩形，并且拥有left, top, right, bottom, x, y, width,
    // 和 height这几个以像素为单位的只读属性用于描述整个边框。除了width 和 height 以外的属性是相对于视图窗口的左上角来计算的
    let rect = ev.target.getBoundingClientRect();
    x = x - rect.left
    y = y - rect.top
    x = -1.0 + x / (canvas.width / 2);
    y = 1.0 - y / (canvas.height / 2);
    return vec2(x, y)
}
